package com.webtest.tag;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/12 17:01
 */
public class ReadFileTag extends SimpleTagSupport {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadFileTag.class);
    //相对于当前WEB应用的根路径的文件名
    private String filePath;

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public void doTag() throws JspException, IOException {
        PageContext context = (PageContext) getJspContext();
        InputStream inputStream = context.getServletContext().getResourceAsStream(filePath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String str = "";
        JspWriter out = context.getOut();
        while ((str = reader.readLine()) != null) {
            LOGGER.info(str);
            Pattern.compile("<").matcher(str).replaceAll("&lt");
            Pattern.compile(">").matcher(str).replaceAll("&gt");
            out.write(str);
            out.write("<br/>");
        }
    }
}
